package com.ly.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ly.system.entity.TbMenu;
import com.ly.system.entity.TbUser;
import com.ly.system.service.TbMenuService;
import com.ly.system.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 罗垭
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService
{

    @Autowired
    private TbUserService sysUserImpl;

    @Autowired
    private TbMenuService sysPermissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //需要构造出 org.springframework.security.core.userdetails.User 对象并返回
       QueryWrapper<TbUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",username);
        TbUser user = sysUserImpl.getOne(queryWrapper);
        if(user==null){
            throw new UsernameNotFoundException(String.format("用户%s不存在",username));
        }
        List<TbMenu> sysPermissions = sysPermissionService.selectListByUser(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        sysPermissions.forEach(sysPermission -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPerms());
            grantedAuthorities.add(grantedAuthority);
        });
        System.out.println(333);
        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);

    }
}
